package visualizer.data;

import java.util.LinkedList;
import java.util.List;

public class DataSource<T> {
	private T data;
	private boolean hasChanged = true;
	private List<DataChangeListener<T>> listeners = new LinkedList<DataChangeListener<T>>();
	
	public DataSource(T data)
	{
		this.data = data;
	}
	
	public synchronized DataSource<T> addListener(DataChangeListener<T> listener)
	{
		listeners.add(listener);
		return this;
	}
	
	public synchronized T get()
	{
		hasChanged = false;
		return data;
	}
	
	public synchronized boolean hasChanged()
	{
		return hasChanged;
	}
	
	public synchronized DataSource<T> set(T data)
	{
		T old = this.data;
		this.data = data;
		hasChanged = true;
		for (DataChangeListener<T> l : listeners) {
			l.dataChanged(old, data);
		}
		return this;
	}
}
